<script setup>
import { getHomeBanner } from '../../../api/home'
import { ref , onMounted } from "vue";
import { Swiper, SwiperSlide } from 'swiper/vue'
import { Pagination, Autoplay } from "swiper/modules"

const swiperDom = ref()
const banners = ref([])
const screenWid = ref(1200)
const modules = [Pagination,Autoplay]
// 切换轮播
const switchSwiper = (type) => {
  if(type === 'prev') {
    mySwiper.value.slidePrev()
  }else {
    mySwiper.value.slideNext()
  }
}
const mySwiper = ref([])
const bindSwiper = (swiper) => {
  mySwiper.value = swiper
}
// 获取首页banner
const homeBanner = () => {
  getHomeBanner().then((res) => {
    banners.value = res.banners
    console.log(banners.value)
  })
}

onMounted(() => {
  homeBanner()
  screenWid.value = window.innerWidth;
  window.addEventListener('resize' , (e) => {
    screenWid.value = window.innerWidth;
  })
})
</script>

<template>
  <div class="home-banner">
    <div class="swiper-prev" @click="switchSwiper('prev')">
      <svg class="icon" aria-hidden="true">
        <use xlink:href="#icon-xiangzuo_o"></use>
      </svg>
    </div>
    <swiper
      :loop="true"
      :space-between="24"
      :slides-per-view="screenWid > 1200 ? 3 : 2"
      :autoplay="{ delay: 4000, disableOnInteraction: true }"
      :pagination="{ type: 'bullets', clickable: true }"
      :scrollbar="{ draggable: true }"
      :modules="modules"
      @swiper="bindSwiper"
      ref="swiperDom"
      class="swiper"
    >
      <swiper-slide v-for="item in banners" :key="item.id" class="swiper-slide">
        <img class="banner-image" :src="item.imageUrl"  alt="banner"/>
      </swiper-slide>
    </swiper>
    <div class="swiper-next" @click="switchSwiper">
      <svg class="icon" aria-hidden="true">
        <use xlink:href="#icon-xiangyoujiantou"></use>
      </svg>
    </div>
  </div>
</template>

<style>
.swiper-pagination-bullet {
  width: 12px !important;
  height: 1px !important;
  border-radius: 2px;
}
.swiper-horizontal > .swiper-pagination-bullets .swiper-pagination-bullet, .swiper-pagination-horizontal.swiper-pagination-bullets .swiper-pagination-bullet {
  margin: 0 2px;
}
.swiper-pagination-bullet-active {
  background: #1b1b1f;
}
</style>
<style scoped lang="scss">
.home-banner {
  width: 100%;
  height: 190px;
  box-sizing: border-box;
  padding: 0 24px;
  position: relative;
}
.swiper {
  width: 100%;
  height: 190px;
}
.swiper-prev {
  width: 14px;
  color: #1b1b1f;
  font-size: 32px;
  z-index: 2;
  cursor: pointer;
  position: absolute;
  left: -10px;
  top: calc(50% - 42px);
}
.swiper-next {
  width: 14px;
  color: #1b1b1f;
  font-size: 26px;
  z-index: 2;
  cursor: pointer;
  position: absolute;
  right: 5px;
  top: calc(50% - 38px);
}
.swiper-slide {
  height: 160px;
}
.banner-image {
  width: 100%;
  height: 160px;
  border-radius: 12px;
}
</style>
